<script>
export default {
  name: "XiaoQuComponent",
  data(){
    return{
      dialogFormVisible: false,
      //获取经纬度的网络请求前缀，需要在后面加上address字符串形式（非数组）
      url:'https://restapi.amap.com/v3/geocode/geo?key=457886b5972a97e93fb9cdccebfd450f&address=',
      //门店名称和详细地址数据,form是对话框中的数据
      form: {
        //小区名字
        name: '',
        //详细地址
        region: '',
        //经纬度
        location:'',
        id:3,
        Users:0,
        shop:0,
        createTime:'',
        address:[],
        //1添加   2修改
        mode:1,
      },
      formArr:[
        {
          name: '门店1',
          region: '详细地址1',
          location:'123,456',
          id:1,
          Users:0,
          shop:0,
          createTime:'2024-07-17 14:11:37',
          address:['河南省']

        },
        {
          name: '门店2',
          region: '详细地址2',
          location:'123,456',
          id:2,
          Users:0,
          shop:0,
          createTime:'2024-07-17 14:11:38',
          address: ['河南省']
        }
      ],
      //搜索框数据
      searchContent:'',
      dateContent:'',
      //输入框标题宽度
      formLabelWidth: '120px',

      //所属地区数据,用于获取经纬度的，不用保存
      addressAll: [],   //省市区
      //address:[], //你选择的地址(废弃)
      //行数据
      row:{},
      index:0
    }
  },
  methods: {
    handleClose(done) {
      this.$confirm('确认关闭？')
          .then(_ => {
            done();
          })
          .catch(_ => {});
    },
    //获取省市
    getAllProvinceAndCityList() {

      // 获取全国所有省份和城市的列表
      var that = this;
      this.$http
          .get("https://restapi.amap.com/v3/config/district", {
            // 高德地图的API
            params: {
              key: "2ebea716638964726dc72279f882d2e4", // 这个是申请的 Key，读者自行写入
              keywords: "中国",
              subdistrict: 3,
              extensions: "base",
            },
          })
          .then((response) => {
            console.log(response.data)


            for(let i = 0;i<response.data.districts[0].districts.length;i++){
              let provinceMap = new Map();
              provinceMap.value = response.data.districts[0].districts[i].adcode;   //区域编号
              provinceMap.label = response.data.districts[0].districts[i].name;     //省名称
              provinceMap.children = [];
              that.addressAll.push(provinceMap);  //添加省份
              for(let j = 0;j < response.data.districts[0].districts[i].districts.length;j++){
                let cityMap = new Map()
                cityMap.value = response.data.districts[0].districts[i].districts[j].adcode;   //区域编号
                cityMap.label = response.data.districts[0].districts[i].districts[j].name;     //市名称
                cityMap.children = [];
                provinceMap.children.push(cityMap); //添加市
                for(let k = 0;k <response.data.districts[0].districts[i].districts[j].districts.length;k++){
                  let areaMap = new Map()
                  areaMap.value = response.data.districts[0].districts[i].districts[j].districts[k].adcode;   //区域编号
                  areaMap.label = response.data.districts[0].districts[i].districts[j].districts[k].name;     //区县名称
                  cityMap.children.push(areaMap);   //添加区县
                }
              }
            }
          });
    },
    //获取坐标
    getLocation(){
      this.axios.get(this.url+this.form.address.join('')).then((response) => {
        console.log(response)
        //axios会自己封装数据，得输出看看
        this.form.location=response.data.geocodes[0].location;
      }).catch((err)=>{
        console.log("请求出错")})
    },
    //将对话框的小区数据加入数组中,确认按钮
    putFormArr(){
      //不应该操作form,因为每次都是对同一个对象的引用，数据不会正确
    /*  this.dialogFormVisible = false;
      console.log(this.form.id)
      this.formArr.push(this.form);
      console.log(this.formArr);
      this.form.id++;*/

      this.dialogFormVisible = false;
      //执行添加
      if (this.form.mode===1){ let newForm={name:this.form.name,region:this.form.region,location:this.form.location,
        id:this.form.id,Users:0,shop:0,createTime:this.formatDateTime(new Date()),address:this.form.address};
        this.formArr.push(newForm);
        this.form.id++;
        console.log(this.formArr)
        this.clearForm();
      }else if (this.form.mode===2){
        //执行编辑
        this.row.name=this.form.name;
        this.row.region=this.form.region;
        this.row.location=this.form.location;
        this.row.address=this.form.address;
        this.form.mode=1;
        this.clearForm();
      }




      },
    //用于清除对话框中的数据
    clearForm(){
      this.form.name='';
      this.form.location='';
      this.form.region='';
      this.form.address=[]
    },
    //格式化日期
    formatDateTime(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    //编辑表格数据
    handleEdit(index, row) {
      console.log(index, row);
      this.dialogFormVisible=true;
      //切换模式
      this.form.mode=2;
      //初始化行数据
       this.row=row;
       this.index=index
      //初始化对话框显示数据
      this.form.name=row.name;
      this.form.region=row.region;
      this.form.address=row.address;
      this.form.location=row.location;



    },
    //删除表格数据
    handleDelete(index, row) {
      console.log(index, row);
      this.formArr.splice(index,1);
    }

    },
  created() {
    // this.getAllProvinceAndCityList();
  }

}


</script>

<template>
<div class="xiaoqu">
  <h1>小区模块组件</h1>
  <div class="searchAndDate cf">
    <div class="search">
      <span>小区名称：</span>
      <el-input v-model="searchContent" placeholder="请输入内容"  class="searchInputSize"></el-input>
    </div>
    <div class="date">
      <span>创建时间：</span>
      <el-date-picker
          v-model="dateContent"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期">
      </el-date-picker>
    </div>
    <el-button type="primary" icon="el-icon-search">搜索</el-button>
  </div>
<!--  对话框-->
  <el-button type="primary" @click="dialogFormVisible = true">新增小区</el-button>
  <el-dialog title="收货地址" :visible.sync="dialogFormVisible">
    <el-form :model="form">
<!--      门店名称-->
      <el-form-item label="门店名称" :label-width="formLabelWidth">
        <el-input v-model="form.name" autocomplete="off"></el-input>
      </el-form-item>
<!--        所属地区-->
      <el-form-item label="所属地区" :label-width="formLabelWidth">
        <div class="areabox" >
          <el-cascader
              :options="addressAll"
              clearable
              v-model="form.address"
              :props="{value:'label'}"

          ></el-cascader>


          <h1>{{form.address}}</h1>
          <h1>{{form.address.join('')}}</h1>
        </div>
      </el-form-item>
        <!--  详细地址-->
      <el-form-item label="" :label-width="formLabelWidth">
        <el-input v-model="form.region" autocomplete="off" placeholder="请填写详细地址"></el-input>
<!--  测试详细地址取值-->
        {{form.region}}
      </el-form-item>

<!--    获取坐标-->
      <el-form-item label="门店坐标" :label-width="formLabelWidth">
        <el-button type="primary" @click="getLocation">获取位置</el-button>{{form.location}}
      </el-form-item>



    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogFormVisible = false">取 消</el-button>
      <el-button type="primary" @click="putFormArr">确 定</el-button>
    </div>
  </el-dialog>
<!--  表格-->
  <el-table
      :data="formArr"
      style="width: 100%"
      :header-cell-style="{'text-align': 'center',backgroundColor: '#1890ff',color:'#fff'}"
      :cell-style="{'text-align': 'center'}"
  >
    <el-table-column
        prop="id"
        label="ID"
        width="180">
    </el-table-column>
    <el-table-column
        prop="name"
        label="名称"
        width="180">
    </el-table-column>
    <el-table-column
        prop="region"
        label="位置">
    </el-table-column>
    <el-table-column
        prop="Users"
        label="用户数量">
    </el-table-column>
    <el-table-column
        prop="shop"
        label="关联门店">
    </el-table-column>
    <el-table-column
        prop="createTime"
        label="创建时间">
    </el-table-column>
    <el-table-column
        label="操作">
      <template slot-scope="scope">
        <el-button
            size="mini"
            @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
        <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.$index, scope.row)">删除</el-button>
      </template>
    </el-table-column>

  </el-table>
  <div class="page">
    <el-pagination
        layout="prev, pager, next"
        :total="2"
        :page-size="10"
    >
    </el-pagination>
  </div>
</div>
</template>

<style scoped>
.xiaoqu{
  height: 800px;
  background-color: hotpink;
}
.search{
  width: 280px;
  height: 36px;
  margin-right: 20px;
  margin-bottom: 10px;
  float: left;
}
.date{
  width: 430px;
  height: 36px;
  margin-right: 20px;
  margin-bottom: 10px;
  float: left;
}
.searchInputSize{
  box-sizing: border-box;
  width: 200px;
  height: 36px;
  padding: 0 15px;
}

.areabox {
  width: 800px;
  display: flex;
  flex-wrap: wrap;
  align-items: center;

}
</style>